package com.lintf.distributed.transaction.inventory.email;

import com.lintf.distributed.transaction.inventory.entity.DeadLetterMessage;
import com.lintf.distributed.transaction.inventory.service.DeadLetterService;
import jakarta.mail.internet.MimeMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
@RefreshScope
@RequiredArgsConstructor
public class NeteaseEmailNotificationService implements EmailNotificationService {
    
    private final JavaMailSender mailSender;
    private final DeadLetterService deadLetterService;
    
    @Value("${spring.mail.username}")
    private String from;
    
    @Value("${deadletter.notify.emails}")
    private List<String> notifyEmails;
    
    @Override
    public void sendDeadLetterNotification(DeadLetterMessage deadLetter) {
        if (CollectionUtils.isEmpty(notifyEmails)) {
            log.warn("未配置死信通知邮箱");
            return;
        }
        
        try {
            MimeMessage message = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            
            helper.setFrom(from);
            helper.setTo(notifyEmails.toArray(new String[0]));
            helper.setSubject("[死信告警]库存扣减失败 - " + deadLetter.getMessageKey());
            helper.setText(buildHtmlContent(deadLetter), true);
            
            mailSender.send(message);
            log.info("死信通知邮件发送成功: id={}", deadLetter.getId());
            
            // 更新通知状态
            deadLetter.setNotified(true);
            deadLetterService.updateById(deadLetter);
            
        } catch (Exception e) {
            log.error("死信通知邮件发送失败: id={}", deadLetter.getId(), e);
        }
    }
    
    private String buildHtmlContent(DeadLetterMessage deadLetter) {
        return String.format(
            "<h3>库存扣减死信通知</h3>" +
            "<div style=\"border:1px solid #eee; padding:15px; border-radius:5px; font-family:Arial,sans-serif\">" +
            "  <p><b>消息ID:</b> %s</p>" +
            "  <p><b>原始主题:</b> %s</p>" +
            "  <p><b>失败时间:</b> %s</p>" +
            "  <p><b>最后尝试:</b> %s (尝试 %d/%d 次)</p>" +
            "  <p><b>失败原因:</b> %s</p>" +
            "  <p><b>业务数据:</b></p>" +
            "  <pre>%s</pre>" +
            "  <p><b>操作链接:</b> <a href=\"%s\">点击处理</a></p>" +
            "</div>" +
            "<p style=\"color:#888;font-size:0.9em\">此邮件由系统自动发送，请勿直接回复</p>",
            deadLetter.getMessageKey(),
            deadLetter.getOriginalTopic(),
            DateFormatUtils.format(deadLetter.getFailureTime(), "yyyy-MM-dd HH:mm:ss"),
            DateFormatUtils.format(deadLetter.getLastRetryTime() != null ? 
                deadLetter.getLastRetryTime() : deadLetter.getFailureTime(), 
                "yyyy-MM-dd HH:mm:ss"),
            deadLetter.getRetryCount(),
            deadLetter.getRetryMax(),
            deadLetter.getFailureReason(),
            StringEscapeUtils.escapeHtml4(deadLetter.getMessageBody()),
            "http://ops.your-company.com/dead-letter/detail/" + deadLetter.getId()
        );
    }
}